package com.example.gcode;

import java.io.IOException;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
 
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.gcode.*;
import com.gcloud.googledrive.ListGoogleFile;
//import com.gcloud.runtime.GCloudSingleton;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.utils.GCloudUtil;

public class Archivos extends ListActivity {

	private ProgressDialog pDialog;
	
	private static final String TAG_NOMBRE = "messages";
    private static final String TAG_SERVICE = "Google Drive";
    Drive service;
    GoogleAccountCredential credential;
    public static final int REQUEST_ACCOUNT_PICKER = 1;
    public static final int REQUEST_AUTHORIZATION = 2;
    public static final int EXECUTE = 3;

    private static Uri fileUri;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.archivos_list);
    
        ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String, String>>();
        for(int i = 0; i<8; i++){
        	HashMap<String, String> map = new HashMap<String, String>();
            
            map.put(TAG_NOMBRE, "prueba"+i);
            map.put(TAG_SERVICE, "Google Drive");
            lista.add(map);
        }
        
        
    	ListAdapter adapter = new SimpleAdapter(
		Archivos.this, lista ,
		R.layout.archivos_list_item, new String[] { TAG_NOMBRE, TAG_SERVICE },
		new int[] { R.id.list_nombre , R.id.list_service});
    	setListAdapter(adapter);   
        
        
    	credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
    	startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
    	registerForContextMenu(this.getListView());
    }

    
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.contextmenu, menu);
    }



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
	    case REQUEST_ACCOUNT_PICKER:
	      if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
	        String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
	        if (accountName != null) {
	          credential.setSelectedAccountName(accountName);
	          service = getDriveServices(credential);
	          new ListGoogleFile(service,
						getApplicationContext()).execute();
	        }
	      }
	      break;
	    case REQUEST_AUTHORIZATION:
	        if (resultCode == Activity.RESULT_OK) {
	        	new ListGoogleFile(service,
						getApplicationContext()).execute();
	        } else {
	          startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
	        }
	        break;
	    	}
	}
	
	private Drive getDriveServices(GoogleAccountCredential credential){
    	return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
	}
	
	class ListGoogleFile extends AsyncTask<Void, Long, Boolean> {

		private Drive service;
		private Context context;
		private final ProgressDialog dialog;
		GCloudSingleton gCloudSingleton;	
		
		public ListGoogleFile(Drive service,
				Context context) {
			this.service = service;
			this.context = context;		
			
			dialog = new ProgressDialog(context);
			
			// if (context != null) {
			// dialog.setMax(100);
			// dialog.setMessage("Getting info from: " + service.getServicePath());
			// dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			// dialog.setProgress(0);
			// dialog.show();
			// }
		}

		protected Boolean doInBackground(Void... params) {
			List<File> result = new ArrayList<File>();
			Files.List request = null;
			try {
				request = service.files().list();
				Log.i("retrieveAllFiles()", "getting files");
			} catch (IOException e1) {
				Log.i("retrieveAllFiles()", "something goes really wrong");
			}
			Log.i("retrieveAllFiles()", "to execute get Files");
			if (request == null) {
				Log.i("retrieveAllFiles() inside run",
						"to execute get Files inside run");
				return false;
			}
			Log.i("retrieveAllFiles()", "request well formed ");
			do {
				try {
					Log.i("ListGoogleFile", "Getting files");
					FileList files = request.execute();
					result.addAll(files.getItems());
					request.setPageToken(files.getNextPageToken());
					Log.i("ListGoogleFile", "Getting files at the end");
				} catch (UserRecoverableAuthIOException e) { 
					startActivityForResult(e.getIntent(), 2);
				}catch (SocketException s) {
					Log.i("ListGoogleFile", " SocketException: " + s);
					return false;
				} catch (IOException e) {
					System.out.println("An error occurred: " + e);
					request.setPageToken(null);
					return false;
				}
			} while (request.getPageToken() != null
					&& request.getPageToken().length() > 0);
			// TODO call singleton here

			if (result != null) {
				gCloudSingleton = GCloudSingleton.getInstance();
				gCloudSingleton.setFilesFromAllService(GCloudUtil
						.googleFilesToGCloudFiles(result));
			}
			// String datasFromFilesD = "";
			for (File file : result) {
				// datasFromFilesD += file.getTitle() + "  ";
				Log.i("RetrieveAllFiles", "File title: " + file.getTitle());
			}
			// showToast(datasFromFilesD);
			return true;
		}

		protected void onPostExecute(Boolean result) {
			dialog.dismiss();
			if (result) {
				runOnUiThread(new Runnable() {
					public void run() {
						/**
						 * Updating parsed JSON data into ListView
						 * */
						GCloudSingleton gSingleton = GCloudSingleton.getInstance();
						Log.i("Archivos:"," "+gSingleton.getFilesFromAllService().size());
						ListAdapter adapter = new SimpleAdapter(Archivos.this,
								gSingleton.getFilesFromAllService(),
								R.layout.archivos_list_item, new String[] {
										TAG_NOMBRE, TAG_SERVICE }, new int[] {
										R.id.list_nombre, R.id.list_service });
						// updating listview
						setListAdapter(adapter);
					}
				});
			} else {
//				startActivityForResult(credential.newChooseAccountIntent(), 2);
//				Intent in = new Intent(null, Archivos.class);
//				in.putExtra("credential", true);
//				Activity ac = (Activity) this.context;
//				ac.startActivity(in);
				Log.i("ListGoogleFile", "getting list unsuccess");
				showToast("Getting List unsuccess");			
			}
		}

		
		
		private void showToast(String message) {
			if (context != null) {
				Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
				toast.show();
			}
		}

	}

}